package com.assetmanage.controller;

import com.assetmanage.model.Asset;
import com.assetmanage.service.AssetService;
import com.assetmanage.service.impl.AssetServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/api/assets/*", "/api/assets"})
public class AssetServlet extends BaseServlet {
    private AssetService assetService = new AssetServiceImpl();

    // 获取所有资产
    public void getAllAssets(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writeSuccess(resp, assetService.getAllAssets());
    }

    // 根据部门ID获取资产
    public void getAssetsByDepartment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String depId = req.getParameter("depId");
        if (depId == null) {
            writeError(resp, "部门ID不能为空");
            return;
        }
        writeSuccess(resp, assetService.getAssetsByDepartment(depId));
    }

    // 根据ID获取资产
    public void getAssetById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String assetId = req.getParameter("assetId");
        if (assetId == null) {
            writeError(resp, "资产ID不能为空");
            return;
        }

        Asset asset = assetService.getAssetById(assetId);
        if (asset != null) {
            writeSuccess(resp, asset);
        } else {
            writeError(resp, "资产不存在");
        }
    }

    // 添加资产
    public void addAsset(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Asset asset = MAPPER.readValue(req.getInputStream(), Asset.class);
        // 确保当前数量等于总数量
        asset.setAssetNum(asset.getTotalNum());
        // 设置初始状态为全部在库
        asset.setAssetStatus("全部在库");

        if (assetService.addAsset(asset)) {
            writeSuccess(resp, null);
        } else {
            writeError(resp, "添加资产失败");
        }
    }

    // 更新资产
    public void updateAsset(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 从URL路径中获取资产ID
            String pathInfo = req.getPathInfo();
            if (pathInfo != null && pathInfo.length() > 1) {
                String assetId = pathInfo.substring(1); // 去掉开头的 '/'
                
                // 读取请求体
                Asset asset = MAPPER.readValue(req.getInputStream(), Asset.class);
                asset.setAssetId(assetId); // 设置从URL中获取的ID
                
                // 更新状态
                if (asset.getAssetNum() == asset.getTotalNum()) {
                    asset.setAssetStatus("全部在库");
                } else if (asset.getAssetNum() == 0) {
                    asset.setAssetStatus("库存为空");
                } else {
                    asset.setAssetStatus("存在库存");
                }

                System.out.println("更新资产: assetId=" + assetId 
                    + ", assetStatus=" + asset.getAssetStatus()
                    + ", assetNum=" + asset.getAssetNum()
                    + ", totalNum=" + asset.getTotalNum());

                if (assetService.updateAsset(asset)) {
                    writeSuccess(resp, null);
                } else {
                    writeError(resp, "更新资产失败");
                }
            } else {
                writeError(resp, "资产ID不能为空");
            }
        } catch (Exception e) {
            writeError(resp, "更新资产失败: " + e.getMessage());
        }
    }

    // 删除资产
    public void deleteAsset(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String assetId = req.getParameter("assetId");
        if (assetId == null) {
            writeError(resp, "资产ID不能为空");
            return;
        }

        if (assetService.deleteAsset(assetId)) {
            writeSuccess(resp, null);
        } else {
            writeError(resp, "该资产存在借用记录，无法删除");
        }
    }

    // 检查资产是否可借用
    public void checkAssetAvailable(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String assetId = req.getParameter("assetId");
        String numStr = req.getParameter("num");
        if (assetId == null || numStr == null) {
            writeError(resp, "资产ID和借用数量不能为空");
            return;
        }

        try {
            int num = Integer.parseInt(numStr);
            writeSuccess(resp, assetService.checkAssetAvailable(assetId, num));
        } catch (NumberFormatException e) {
            writeError(resp, "借用数量必须是数字");
        }
    }

    // 借用审批时更新资产
    public void permitUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 从URL路径中获取资产ID
            String pathInfo = req.getPathInfo();
            if (pathInfo != null && pathInfo.length() > 1) {
                String assetId = pathInfo.substring(1); // 去掉开头的 '/'
                
                // 读取请求体中的借用数量和操作类型
                Asset requestData = MAPPER.readValue(req.getInputStream(), Asset.class);
                int borrowNum = requestData.getAssetNum(); // 这里的assetNum实际上是借用数量
                String operationType = requestData.getAssetStatus(); // 使用assetStatus字段传递操作类型：lendout或return
                
                // 获取当前资产信息
                Asset currentAsset = assetService.getAssetById(assetId);
                if (currentAsset == null) {
                    writeError(resp, "资产不存在");
                    return;
                }

                // 保存当前资产的所有字段
                String assetName = currentAsset.getAssetName();
                String depId = currentAsset.getDepId();
                int totalNum = currentAsset.getTotalNum();
                int currentNum = currentAsset.getAssetNum();
                
                // 根据操作类型更新资产数量
                if ("lendout".equals(operationType)) {
                    // 借出操作，检查是否超过当前可用数量
                    if (borrowNum > currentNum) {
                        writeError(resp, "借出数量超过当前可用数量");
                        return;
                    }
                    currentNum = currentNum - borrowNum;
                } else if ("return".equals(operationType)) {
                    // 归还操作，检查是否超过总库存
                    if (currentNum + borrowNum > totalNum) {
                        writeError(resp, "归还后数量将超过总库存");
                        return;
                    }
                    currentNum = currentNum + borrowNum;
                } else {
                    writeError(resp, "无效的操作类型");
                    return;
                }

                // 检查更新后的数量是否合法
                if (currentNum < 0) {
                    writeError(resp, "更新后的数量不能小于0");
                    return;
                }
                
                // 重新设置所有字段
                currentAsset.setAssetId(assetId);
                currentAsset.setAssetName(assetName);
                currentAsset.setDepId(depId);
                currentAsset.setTotalNum(totalNum);
                currentAsset.setAssetNum(currentNum);
                
                // 更新状态
                if (currentNum == totalNum) {
                    currentAsset.setAssetStatus("全部在库");
                } else if (currentNum == 0) {
                    currentAsset.setAssetStatus("库存为空");
                } else {
                    currentAsset.setAssetStatus("存在库存");
                }

                System.out.println("借用审批更新资产: assetId=" + assetId 
                    + ", assetName=" + assetName
                    + ", depId=" + depId
                    + ", 操作类型=" + operationType
                    + ", 操作数量=" + borrowNum
                    + ", 更新后可用数量=" + currentNum
                    + ", 总数量=" + totalNum
                    + ", 更新后状态=" + currentAsset.getAssetStatus());

                if (assetService.updateAsset(currentAsset)) {
                    writeSuccess(resp, null);
                } else {
                    writeError(resp, "更新资产失败");
                }
            } else {
                writeError(resp, "资产ID不能为空");
            }
        } catch (Exception e) {
            writeError(resp, "更新资产失败: " + e.getMessage());
        }
    }
} 